<!-- 树状选择器 -->
<template>
  <el-popover
    ref="popover"
    v-model="showStatus"
    class="select-tree-box"
    transition="el-zoom-in-top"
    popper-class="select-tree-box-new"
    placement="bottom-start"
    trigger="click"
    :disabled="disabled || (elForm && elForm.disabled)"
    @show="onShowPopover"
    @hide="onHidePopover">
    <el-input v-model="filterValue" class="select-tree-filter" placeholder="输入关键字进行过滤" />
    <el-tree
      ref="tree"
      class="select-tree"
      node-key="id"
      icon-class="el-icon-arrow-right"
      :style="`min-width: ${treeWidth}`"
      :data="data"
      :props="props"
      :expand-on-click-node="false"
      :default-expanded-keys="defaultExpandKeys"
      :filter-node-method="filterNode"
      render-after-expand
      @node-click="onClickNode" />
    <el-input
      slot="reference"
      ref="input"
      v-model="labelModel"
      :clearable="!!valueModel"
      :disabled="disabled"
      :style="`width: ${width}px`"
      class="pointer-events-child-no"
      :class="{ 'rotate': showStatus }"
      suffix-icon="el-icon-arrow-down"
      :placeholder="placeholder"
      @clear="clearValue" />
  </el-popover>
</template>

<script>
export default {
  name: 'SelectTree',
  // 设置绑定参数
  model: {
    prop: 'value',
    event: 'selected'
  },
  props: {
    // popover是否可用
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否有单点回调
    nodeClick: {
      type: Boolean,
      required: false,
      default: false
    },
    // 接收绑定参数
    value: String,
    // 输入框宽度
    width: String,
    // 选项数据
    options: {
      type: Array,
      required: true
    },
    // 输入框占位符
    placeholder: {
      type: String,
      required: false,
      default: '请选择'
    },
    // 树节点配置选项
    props: {
      type: Object,
      required: false,
      default: () => ({
        parent: 'parentId',
        value: 'rowGuid',
        label: 'areaName',
        children: 'children'
      })
    }
  },
  inject: ['elForm'],
  data() {
    return {
      filterValue: '', // 筛选
      // 树状菜单显示状态
      showStatus: false,
      // 菜单宽度
      treeWidth: 'auto',
      // 输入框显示值
      labelModel: '',
      // 实际请求传值
      // valueModel: null
      valueModel: this.value,
      defaultExpandKeys: []
    }
  },
  computed: {
    // 是否为树状结构数据
    dataType() {
      const jsonStr = JSON.stringify(this.options)
      return jsonStr.indexOf(this.props.children) !== -1
    },
    // 若非树状结构，则转化为树状结构数据
    data() {
      return this.dataType ? this.options : this.switchTree()
    }
  },
  watch: {
    labelModel(val) {
      if (!val) {
        this.valueModel = ''
      }
      // this.$refs.tree.filter(val)
    },
    value(val) {
      this.valueModel = val
      this.labelModel = this.queryTree(this.data, val)
    },
    options: {
      handler(val) {
        if (val) {
          this.labelModel = this.queryTree(val, this.value)

          // 默认展开前两层
          const valueKey = this.props.value
          const childrenKey = this.props.children
          this.defaultExpandKeys = val.reduce((result, item) => {
            item[valueKey] && result.push(item[valueKey])
            if (item[childrenKey]) {
              result.push(...item[childrenKey].map(child => child[valueKey]))
            }
            return result
          }, [])
        }
      },
      immediate: true
    },
    filterValue(val) {
      this.$refs.tree && this.$refs.tree.filter(val)
    }
  },
  created() {
    // 检测输入框原有值并显示对应 label
    this.labelModel = this.queryTree(this.data, this.value)
    // 获取输入框宽度同步至树状菜单宽度
    this.$nextTick(() => {
      this.treeWidth = `${(this.width || this.$refs.input.$refs.input.clientWidth) - 24}px`
    })
  },
  methods: {
    // 单击节点
    onClickNode(node, node1, node2) {
      if (node.disabled) return
      this.labelModel = node[this.props.label]
      this.valueModel = node[this.props.value]
      // 如果有回调就到父页面回调
      if (this.nodeClick) {
        this.$emit('nodeClick', this, node)
      }
      this.onCloseTree()
    },
    clearValue() {
      this.$emit('clear', this)
    },
    // 偏平数组转化为树状层级结构
    switchTree() {
      return this.cleanChildren(this.buildTree(this.options, '0'))
    },
    // 隐藏树状菜单
    onCloseTree() {
      // this.$refs.popover.showPopper = false
      this.showStatus = false
    },
    // 显示时触发
    onShowPopover() {
      this.showStatus = true
      // this.$refs.tree.filter(false)
      if (this.data && this.data[0] && this.data[0][this.props.value] === '') {
        // 在最外层加了空值  清空选项是高亮
        this.$refs.tree.setCurrentKey(this.valueModel)
      } else {
        this.$refs.tree.setCurrentKey(this.valueModel || null)
      }
    },
    // 隐藏时触发
    onHidePopover() {
      this.showStatus = false
      this.filterValue = ''
      this.$emit('selected', this.valueModel)
    },
    // 树节点过滤方法
    filterNode(query, data) {
      if (!query) return true
      return data[this.props.label].indexOf(query) !== -1
    },
    // 搜索树状数据中的 ID
    queryTree(tree, id) {
      let stark = []
      stark = stark.concat(tree)
      while (stark.length) {
        const temp = stark.shift()
        if (temp[this.props.children]) {
          stark = stark.concat(temp[this.props.children])
        }
        if (id && temp[this.props.value] === id) {
          this.$refs.tree && this.$refs.tree.setCurrentKey(id)
          return temp[this.props.label]
        }
      }
      return ''
    },
    // 将一维的扁平数组转换为多层级对象
    buildTree(data, id = '0') {
      const fa = (parentId) => {
        const temp = []
        for (let i = 0; i < data.length; i++) {
          const n = data[i]
          if (n[this.props.parent] === parentId) {
            n.children = fa(n.rowGuid)
            temp.push(n)
          }
        }
        return temp
      }
      return fa(id)
    },
    // 清除空 children项
    cleanChildren(data) {
      const fa = (list) => {
        list.map((e) => {
          if (e.children.length) {
            fa(e.children)
          } else {
            delete e.children
          }
          return e
        })
        return list
      }
      return fa(data)
    },
    // 添加树节点
    appendNode(data, id) {
      this.$refs.tree.append(data, id)
    },
    // 修改树节点名称lable
    updateNode(id, name) {
      if (this.$refs.tree.getNode(id)) {
        this.$refs.tree.getNode(id).data.label = name
      }
    },
    // 删除树节点
    removeNode(id) {
      this.$refs.tree.remove(id)
    }
  }
}
</script>

<style lang="scss">
.select-tree-box-new{
  max-height: 400px;
  overflow: auto;
}
.select-tree-filter{
  margin-bottom: 10px;
}
.select-tree {
  max-height: 325px;
  overflow-y: scroll;
}
.select-tree-box{
  .el-input.el-input--suffix {
    cursor: pointer;
    overflow: hidden;
  }
  .el-input.el-input--suffix.rotate .el-icon-arrow-down {
    transform: rotate(180deg);
  }
  .pointer-events-child-no .el-input__inner{
    pointer-events: none;
  }
  /* 菜单滚动条 */
  .select-tree::-webkit-scrollbar {
    z-index: 11;
    width: 6px;
  }
  .select-tree::-webkit-scrollbar-track,
  .select-tree::-webkit-scrollbar-corner {
    background: #fff;
  }
  .select-tree::-webkit-scrollbar-thumb {
    border-radius: 5px;
    width: 6px;
    background: #b4bccc;
  }
  .select-tree::-webkit-scrollbar-track-piece {
    background: #fff;
    width: 6px;
  }
}
.select-tree{
  .el-tree-node[aria-disabled="true"]{
    &:focus{
      > .el-tree-node__content{
        background: none;
      }
    }
    > .el-tree-node__content{
      cursor: no-drop;
      color: #C0C4CC;
      &:hover{
        background: none;
      }
      // .el-tree-node__expand-icon.is-leaf{
      //   background: url(../../assets/images/tree-node-leaf-icon.png) center/contain no-repeat;
      // }
    }
  }
}
</style>
